<?php

namespace app\api\controller\v1;

use app\admin\model\SystemConfig;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\model\MallAccountLog;
use app\common\model\MallBonus;
use app\common\model\MallCollect;
use app\common\model\MallDoorGoods;
use app\common\model\MallFeedback;
use app\common\model\MallGoods;
use app\common\model\MallHistory;
use app\common\model\MallManager;
use app\common\model\MallManagerDoor;
use app\common\model\MallMessage;
use app\common\model\MallOrder;
use app\common\model\MallSpecsValue;
use app\common\model\MallUser;
use app\common\model\MallUserAddress;
use app\common\model\MallUserBonus;
use app\common\model\MallWithdrawal;
use think\facade\Log;
use think\facade\Validate;

class User extends Base
{

    /**
     * 更新用户信息
     * @return \think\response\Json
     */
    public function updateByUserInfo()
    {
        $avatarUrl = $this->request->param('avatarUrl', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');
        $nickName = $this->request->param('nickName', '', 'trim');
        $realname = $this->request->param('realname', '', 'trim');
        $sex = $this->request->param('sex', '', 'trim');
        $data=['update_time'=>time()];
        if($avatarUrl){
            $data['avatarUrl'] =$avatarUrl;
        }
        if($nickName){
            $data['nickName'] =htmlspecialchars_decode($nickName);
        }
        if($realname){
            $data['realname'] =$realname;
        }
        if($sex){
            $data['sex'] =$sex;
        }
        //查询用户是否存在
        try {
            $user = (new MallUser())->getBaseByWhereOne([['openid','=',$openid]],'*');
        } catch (\Exception $e) {
            Log::error("user_update:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if (!$user) {
            return Show::json_show(Status::mini_error, "请关闭重试");
        }

        try {
            $result = (new MallUser())->where("id",'=',$user['id'])->save($data);
        } catch (\Exception $e) {
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }

        if ($result) {
            try {
                $wechat = (new MallUser())->getBaseById($user['id']);
            } catch (\Exception $e) {
                Log::error("user_update:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
                return Show::json_show(Status::mini_error, "发生错误");
            }
            if ($wechat) {
                return Show::json_show(Status::mini_normal, "操作成功", $wechat);
            } else {
                return Show::json_show(Status::mini_error, "内部错误");
            }
        } else {
            return Show::json_show(Status::mini_error, "操作失败");
        }
    }


    /**
     * 用户信息接口
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function getUserInfo(){
        $openid =$this->request->param('openid','','trim');
        try{
            $userinfo =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]],'id,openid,nickName,realname,sex,mobile,avatarUrl,balance,income,ishx,status,ismanager');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$userinfo){
            return Show::json_show(Status::mini_error,'用户信息有误');
        }
        $messagecount= (new MallMessage())->getBaseByWhereCount([['touser','=',$openid],['isread','=',0]]);
        $userinfo['mcount'] =$messagecount;
        $shop =(new MallManager())->where([['openid','=',$openid]])->find();
        if($shop){
            $userinfo['shoptitle'] = $shop['title'];
            $userinfo['shoplogo'] = $shop['logo'];
            $userinfo['applystatus'] =$shop['status'];
            $userinfo['m_image'] =$shop['m_image'];
        }else{
            $userinfo['shoptitle'] = $userinfo['nickName'];
            $userinfo['shoplogo'] = $userinfo['avatarUrl'];
            $userinfo['applystatus'] ='-1';
            $userinfo['m_image'] ='';
        }

        return Show::json_show(Status::mini_normal,'ok',[
           'users'=>$userinfo
        ]);
    }

    /**
     * 我的消息
     * @return \think\response\Json
     */
    public function myMessage(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page',1,'intval');
        $limit =$this->request->param('limit',10,'intval');
        try{
            $list =(new MallMessage())->getBaseBylistPage([['touser','=',$openid],['status','=',1]],$page,$limit,'id,content');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'list'=>$list
        ]);
    }

    public function  getOrderCount(){
        $openid =$this->request->param('openid','','trim');
        try{
            $allcount =(new MallOrder())->getBaseByWhereCount([['openid','=',$openid]]);
            $unpaycount =(new MallOrder())->getBaseByWhereCount([['openid','=',$openid],['status','=',0]]);
            $unhxcount =(new MallOrder())->getBaseByWhereCount([['openid','=',$openid],['status','=',1]]);
            $donecount =(new MallOrder())->getBaseByWhereCount([['openid','=',$openid],['status','=',2]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'order'=>['allcount'=>$allcount,'unpaycount'=>$unpaycount,'unhxcount'=>$unhxcount,'donecount'=>$donecount]
        ]);
    }



    /**
     * 消息详情
     * @return \think\response\Json
     */
    public function messageInfo(){
        $id =$this->request->param('id','','intval');
        try{
            $info =(new MallMessage())->getBaseById($id,'id,content,isread,create_time');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$info){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if($info['isread'] ==0){
            (new MallMessage())->where([['id','=',$id]])->save(['isread'=>1]);
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'detail'=>$info
        ]);
    }

    /**
     * 我的订单记录
     * @return \think\response\Json
     */
    public function getOrders(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page',1,'intval');
        $limit =$this->request->param('limit',10,'intval');
        $status =$this->request->param('status',-1,'intval');
        $where=[['openid','=',$openid]];
        if($status!=-1){
            $where[]=[['status','=',$status]];
        }
        try{
            $orders =(new MallOrder())->getBaseBylistPage($where,$page,$limit,'id,orderno,status,goods_logo,goods_title,short_title,goods_price,goods_num,orderprice,payprice,hx_time');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if($orders){
            foreach ($orders as $k=>$v){
                switch ($v['status']){
                    case 0:
                        $orders[$k]['statusname'] ='待付款';
                        break;
                    case 1:
                        $orders[$k]['statusname'] ='待核销';
                        break;
                    case 2:
                        $orders[$k]['statusname'] ='已完成';
                        break;
                    case 3:
                        $orders[$k]['statusname'] ='过期未核销';
                        break;
                    case 4:
                        $orders[$k]['statusname'] ='已失效';
                        break;
                    default:
                        break;
                }
            }
        }

        return Show::json_show(Status::mini_normal,'ok',[
           'order'=>$orders
        ]);
    }

    /**
     * 我的订单记录
     * @return \think\response\Json
     */
    public function getOrdersV2(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page',1,'intval');
        $limit =$this->request->param('limit',10,'intval');
        $status =$this->request->param('status',-1,'intval');
        $where=[['openid','=',$openid]];
        if($status!=-1){
            $where[]=[['status','=',$status]];
        }
        try{
            $orders =(new MallOrder())->getBaseBylistPage($where,$page,$limit,'id,orderno,status,goods_logo,goods_title,short_title,specs_value_ids,goods_price,goods_num,orderprice,payprice,hx_time');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if($orders){
            foreach ($orders as $k=>$v){
                switch ($v['status']){
                    case 0:
                        $orders[$k]['statusname'] ='待付款';
                        break;
                    case 1:
                        $orders[$k]['statusname'] ='待核销';
                        break;
                    case 2:
                        $orders[$k]['statusname'] ='已完成';
                        break;
                    case 3:
                        $orders[$k]['statusname'] ='已退款';
                        break;
                    case 4:
                        $orders[$k]['statusname'] ='已失效';
                        break;
                    default:
                        break;
                }

                $orders[$k]['option_name'] =$this->getGetSpecsValueIdsAttr($v['specs_value_ids']);
            }
        }

        return Show::json_show(Status::mini_normal,'ok',[
            'order'=>$orders
        ]);
    }

    protected function getGetSpecsValueIdsAttr($value){

        if(empty($value)){
            return '默认';
        }
        $ids = explode("-",$value);
        $res= (new MallSpecsValue())->where('id','in',$ids)
            ->select()->toArray();
        $options= '';
        foreach ($res as $k=>$v){
            $options.= $v['title'].' ';
        }
        return $options;
    }
    /**
     * 我的订单记录
     * @return \think\response\Json
     */
    public function getManagerOrders(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page',1,'intval');
        $limit =$this->request->param('limit',10,'intval');
        $status =$this->request->param('status',0,'intval');
        $keyword =$this->request->param('keyword','','trim');
        $starttime =$this->request->param('starttime','','trim');
        $endtime =$this->request->param('endtime','','trim');
        $where=[];
        if($status>0){
            $where[]=[['status','=',$status]];
        }else{
            $where[]=[['status','in',[1,2]]];
        }
        if($keyword){
            $where[] =[['orderno','like','%'.$keyword.'%']];
        }
        if($starttime){
            $where[] =[['create_time','<',strtotime($starttime)]];
        }
        if($endtime){
            $where[] =[['create_time','>',strtotime($endtime)]];
        }

        $manager=(new MallManager())->getBaseByWhereOne([['openid','=',$openid]]);
        if($manager && $manager['status'] ==1){
            $where[] =[['manager_id','=',$manager['id']]];
            try{
                $orders =(new MallOrder())->getBaseBylistPage($where,$page,$limit,'id,orderno,status,goods_logo,specs_value_ids,goods_title,short_title,goods_price,goods_num,orderprice,payprice,hx_time');
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error,'查询失败');
            }
            if($orders){
                foreach ($orders as $k=>$v){
                    switch ($v['status']){
                        case 1:
                            $orders[$k]['statusname'] ='待核销';
                            break;
                        case 2:
                            $orders[$k]['statusname'] ='已核销';
                            break;

                        default:
                            break;
                    }
                    if($v['specs_value_ids']){
                        $orders[$k]['option_name'] =$this->getGetSpecsValueIdsAttr($v['specs_value_ids']);
                    }else{
                        $orders[$k]['option_name']='';
                    }
                }
            }
        }else{
            $orders =[];
        }


        return Show::json_show(Status::mini_normal,'ok',[
            'order'=>$orders
        ]);
    }


    /**
     * 订单详情接口
     * @return \think\response\Json
     */
    public function orderDetail(){
        $order_id =$this->request->param('order_id','','intval');
        try{
            $detail =(new MallOrder())->getBaseById($order_id,'id,orderno,goods_id,validity_time,status,bonus_price,specs_value_ids,goods_title,short_title,goods_logo,goods_num,market_price,goods_price,orderprice,discount,payprice,bonus_price,realname,mobile,doors,create_time,pay_type,pay_time,hx_time,status');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }

        if(!$detail){
            return Show::json_show(Status::mini_error,'订单不存在');
        }

        $option_name ='';
        if($detail['specs_value_ids']){
            $option_name =$this->getGetSpecsValueIdsAttr($detail['specs_value_ids']);
        }
        $detail['option_name'] =$option_name;
        switch ($detail['status']){
            case 0:
                $detail['statusname'] ='待付款';
                break;
            case 1:
                $detail['statusname'] ='待核销';
                break;
            case 2:
                $detail['statusname'] ='已完成';
                break;
            case 3:
                $detail['statusname'] ='已退款';
                break;
            case 4:
                $detail['statusname'] ='已失效';
                break;
            default:
                break;
        }

        $doors =(new MallDoorGoods())->getBaseByWhere([['goods_id','=',$detail['goods_id']]]);
        $detail['doorsnum'] =count($doors);
        $doorInfo =[];
        if(count($doors)>0){
            if($doors[0]['door_id']>0){
                $doorInfo =(new MallManagerDoor())->alias('d')->field('d.id,d.title,m.logo,d.mobile,d.latlng,m_image,d.province,d.city,d.county,d.location,d.store_no,d.opentime')
                    ->join('mall_manager m','m.id=d.manager_id')
                    ->where([['d.id','=',$doors[0]['door_id']]])->find()->toArray();
                $lats =explode(',',$doorInfo['latlng']);
                $doorInfo['lat'] =$lats[0];
                $doorInfo['lng'] =$lats[1];
            }
        }

        $detail['doorInfo'] =$doorInfo;
        if($detail['pay_time']>0){
            $detail['paytime'] =date('Y-m-d H:i:s',$detail['pay_time']);
        }else{
            $detail['paytime']='';
        }
        if($detail['hx_time']>0){
            $detail['hxtime'] =date('Y-m-d H:i:s',$detail['hx_time']);
        }else{
            $detail['hxtime']='';
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'detail'=>$detail
        ]);
    }

    /**
     * 提现操作
     * @return \think\response\Json
     */
    public function doWithdrawal(){
        $openid = $this->request->param('openid', '', 'trim');
        $money= $this->request->param('money', '0', 'trim');
        $realname= $this->request->param('realname', '', 'trim');
        $bankno= $this->request->param('bankno', '', 'trim');
        $bankname= $this->request->param('bankname', '', 'trim');

        try{
            $user =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
            $manager=(new MallManager())->getBaseByWhereOne([['openid','=',$openid],['status','=',1]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$user){
            return Show::json_show(Status::mini_error,'系统异常');
        }
        if($user['balance'] <$money){
            return Show::json_show(Status::mini_error,'余额不足,申请失败');
        }
        $model =(new MallWithdrawal());
        $model->startTrans();
        try{
            $data=[
                'openid'   =>$openid,
                'ordersn'  =>Str::RandomStr(),
                'manager_name'=>!empty($manager)?$manager['title']:'',
                'money'    =>$money,
                'realname' =>$realname,
                'bankno'   =>$bankno,
                'bankname'  =>$bankname,
                'status'   =>0,
                'datetime' =>date('Y-m'),
                'dotype'   =>2, // 手动打款
                'typedesc' =>'提现'
            ];
            (new MallWithdrawal())->save($data);
            (new MallUser())->where("id",'=',$user['id'])->Dec('balance',$money)->update();
        }catch (\Exception $e){
            $model->rollback();
            return Show::json_show(Status::mini_error,'查询失败');
        }
        $model->commit();
        return Show::json_show(Status::mini_normal,'ok',[
            'ordersn'=>$data['ordersn']
        ]);
    }

    /**
     * 提现记录
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function getWithdrawalLog(){
        $openid = $this->request->param('openid', '', 'trim');
        $yearmonth = $this->request->param('yearmonth', '', 'trim');
        $where =[];
        if(!empty($yearmonth)){
            $where[]=[['datetime','=',$yearmonth]];
        }
        $where[] =[['openid','=',$openid]];
        try{
            $user =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
            $log =(new MallWithdrawal())->field('datetime')->where($where)->group('datetime')->order('id desc')->select()->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$user){
            return Show::json_show(Status::mini_error,'会员不存在');
        }
        $logs=[];
        if(count($log)>0){
            foreach ($log as $k=>$v){
                if($v['datetime'] == date('Y-m')){
                    $logs[$k]['datetime'] ='本月';
                }else{
                    $logs[$k]['datetime'] =date('Y年m月',strtotime($v['datetime']));
                }

                $child= (new MallWithdrawal())->getBaseByWhere($where,'id,typedesc,money,create_time,status','id desc');
                foreach ($child as $kk=>$vv){
                    switch ($vv['status']){
                        case 0:
                            $child[$kk]['statusname'] ='审核中';
                            break;
                        case 1:
                            $child[$kk]['statusname'] ='已提现';
                            break;
                        case 2:
                            $child[$kk]['statusname'] ='审核失败';
                            break;
                        default:
                            break;
                    }
                }
                $logs[$k]['child']=$child;
            }
        }
        if(!$user){
            return Show::json_show(Status::mini_error,'系统异常');
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'logs'=>$logs
        ]);
    }


    /**
     * 收藏记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function  getMyCollect(){
        $openid = $this->request->param('openid', '', 'trim');
        $page = $this->request->param('page', 1, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        try{
            $user =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
            $product =(new MallCollect())->alias('c')
                ->field('p.id,p.title,p.goods_price,p.logo')
                ->join('mall_goods p','p.id=c.product_id')
                ->where("c.openid='$openid'")
                ->page($page,$limit)
                ->order('c.id desc')
                ->select()
                ->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$user){
            return Show::json_show(Status::mini_error,'会员不存在');
        }

        return Show::json_show(Status::mini_normal,'ok',[
            'product'=>$product
        ]);
    }

    /**
     * 浏览记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function  getMyHistory(){
        $openid = $this->request->param('openid', '', 'trim');
        $page = $this->request->param('page', 1, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        try{
            $user =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
            $product =(new MallHistory())->alias('c')
                ->field('p.id,p.title,p.goods_price,p.logo')
                ->join('mall_goods p','p.id=c.goods_id')
                ->where("c.openid='$openid'")
                ->page($page,$limit)
                ->order('c.id desc')
                ->select()
                ->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$user){
            return Show::json_show(Status::mini_error,'会员不存在');
        }
        foreach ($product as $k=>$v){
            $cinfo =(new MallCollect())->where([['openid','=',$openid],['product_id','=',$v['id']]])->find();
            $product[$k]['iscollect'] =!empty($cinfo)?1:0;
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'product'=>$product
        ]);
    }

    /**
     * 加入收藏接口
     * @return \think\response\Json
     */
    public function addcollect(){
        $openid = $this->request->param('openid', '', 'trim');
        $id =$this->request->param('goods_id','','intval');

        try{
            $goods =(new MallGoods())->getBaseById($id);
            $collect =(new MallCollect())->getBaseByWhereOne([['product_id','=',$id],['openid','=',$openid]]);

        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$goods){
            return Show::json_show(Status::mini_error,'查询失败');
        }

        if($collect){
            $row =(new MallCollect())->find($collect['id']);
            $row->delete();
            return Show::json_show(Status::mini_normal,'取消收藏成功',['iscollect'=>0]);
        }else{
            try{
                (new MallCollect())->save(['openid'=>$openid,'product_id'=>$id]);
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error,'查询失败');
            }
            return Show::json_show(Status::mini_normal,'新增收藏成功',['iscollect'=>1]);
        }
    }

    /**
     * 意见反馈接口
     * @return \think\response\Json
     */
    public function getMyfeedback(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page',1,'intval');
        $limit =$this->request->param('limit',10,'intval');
        try{
            $list =(new MallFeedback())->where([['openid','=',$openid]])->page($page,$limit)->select()->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }

        return Show::json_show(Status::mini_normal,'ok',[
           'list'=>$list??[]
        ]);
    }

    /**
     * 发表意见接口
     * @return \think\response\Json
     */
    public function addFeedback(){
        $openid =$this->request->param('openid','','trim');
        $mobile =$this->request->param('mobile','','trim');
        $content =$this->request->param('content','','trim');
        if(!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)){
            return Show::json_show(Status::mini_error,'手机号格式有误');
        }

        try{
            (new MallFeedback())->save(['mobile'=>$mobile,'content'=>$content,'openid'=>$openid]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        return Show::json_show(Status::mini_normal,'ok',[

        ]);
    }

    /**
     * 领取红包接口
     * @return \think\response\Json
     */
    public function addBonus(){
        $openid =$this->request->param('openid','','trim');
        $id =$this->request->param('bonus_id','','intval');
        try{
            $bonus =(new MallBonus())->getBaseById($id);
            $mybonus =(new MallUserBonus())->getBaseByWhereOne([['openid','=',$openid],['bonus_id','=',$id],['used','=',0]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$bonus){
            return Show::json_show(Status::mini_error,'该红包不存在');
        }
        if(!$mybonus){
            $data =[
               'openid'=>$openid,
               'bonus_id' =>$id,
               'used'=>0,
               'orderno'=>''
            ];
            (new MallUserBonus())->save($data);
        }
        return Show::json_show(Status::mini_normal,'ok',[]);
    }

    /**
     * 我的红包接口
     * @return \think\response\Json
     */
    public function getMyBonus(){
        $openid =$this->request->param('openid','','trim');
        $type   =$this->request->param('type',0,'intval'); // 0 未使用  1使用 2已过期
        $page   =$this->request->param('page',1,'intval');
        $limit  =$this->request->param('limit',10,'intval');
        $where =[['ub.openid','=',$openid]];
        if(in_array($type,[0,1])){
            $where[] =[['ub.used','=',$type]];
        }else{
            $where[] =[['b.endtime','<',time()]];
        }
        try{
            $list =(new MallUserBonus())->alias('ub')
                  ->field('b.id,b.title,ub.used,b.money,FROM_UNIXTIME(b.starttime,"%Y-%m-%d") as starttime,FROM_UNIXTIME(b.endtime,"%Y-%m-%d") as endtime')
                ->join('mall_bonus b','b.id=ub.bonus_id')
                ->where($where)
                ->page($page,$limit)
                ->select()->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(count($list)>0){
            foreach ($list as $k=>$v){
                if($v['used'] ==1){
                    $list[$k]['status'] =1;
                }
               if(strtotime($v['starttime'])<time() && time()<strtotime($v['endtime']) ){
                   if($v['used'] ==0){
                       $list[$k]['status'] =0;
                   }
               }else{
                   $list[$k]['status'] =2;
               }
            }
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'list'=>$list
        ]);
    }

    /**
     * 获取所有
     * @return \think\response\Json
     */
    public function getAddressByInfo()
    {
        $openid = $this->request->param('openid', '', 'trim');

        try {
            $address = (new MallUserAddress())->getBaseByWhere([['openid','=',$openid]]);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询地址错误");
        }
        return Show::json_show(Status::mini_normal, "ok", $address);
    }

    /**
     * 新增
     * @return \think\response\Json
     */
    public function addAddress()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $realname = $this->request->param('realname', '', 'trim');
        $mobile = $this->request->param('mobile', '', 'trim');
        $locatarea = $this->request->param('locatarea', '', 'trim');
        $address = $this->request->param('address', '', 'trim');
        $cityarea = $this->request->param('cityarea', '', 'trim');
        $areacode = $this->request->param('areacode', '', 'trim');
        $is_default = $this->request->param('isdefault', 0, 'intval');
        $id = $this->request->param('id',0,'intval');

        $validate = Validate::rule([
            'realname' => "require",
            "mobile" => "require|mobile",
            "cityarea" => "require",
            "address" => "require",
        ])->message([
            "realname.require" => "请输入姓名",
            "mobile.require" => "请输入手机号",
            "mobile.mobile" => "手机号不正确",
            "cityarea.require" => "请选择省市区",
            "address.require" => "请选择地址",
        ]);
        $data = [
            "realname" => $realname,
            "mobile" => $mobile,
            "address" => $address,
            "cityarea" =>$cityarea,
            "areacode" =>$areacode,
            "isdefault" => $is_default,
            "openid" => $openid
        ];

        if (!$validate->check($data)) {
            return Show::json_show(Status::mini_error, $validate->getError());
        }

        //先更新其他
        $this->modelObj =(new MallUserAddress());
        $this->modelObj->startTrans();
        try {
            $this->modelObj->where('openid', $openid)
                ->update([
                    "isdefault" => 0,
                    "update_time" => time()
                ]);
            if($id>0){
                $this->modelObj->where("id",$id)->save($data);
            }else{
                $this->modelObj->save($data);
            }
            $this->modelObj->commit();
        } catch (\Exception $e) {
            $this->modelObj->rollback();
            Log::error("user_update:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "操作失败");
        }
        return Show::json_show(Status::mini_normal, "ok");
    }

    /**
     * 提交认证接口
     * @return \think\response\Json
     */
    public function applyToManager(){
        $openid =$this->request->param('openid','','trim');
        $title =$this->request->param('title','','trim');
        $realname =$this->request->param('realname','','trim');
        $mobile =$this->request->param('mobile','','trim');
        $cardimg =$this->request->param('cardimg','','trim');

        if(!$title || !$realname || !$mobile || empty($cardimg)){
            return Show::json_show(Status::mini_error,'请填写完整认证信息');
        }
        if(!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)){
            return Show::json_show(Status::mini_error,'手机号格式有误');
        }

        try{
            $user =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
            $manager =(new MallManager())->getBaseByWhereOne([['openid','=',$openid]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$user){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        $m_images ='';
        foreach ($cardimg as $k=>$v){
            $m_images.=$v['url'].'|';
        }
        if($m_images){
            $m_images =substr($m_images,0,-1);
        }

        $data =[
            'openid'=>$openid,
            'title' =>$title,
            'realname' =>$realname,
            'mobile'   =>$mobile,
            'm_image' =>$m_images,
            'logo' =>'https://'.$_SERVER['HTTP_HOST'].'/static/logo.png',
            'status'=>0
        ];
        try{
            if($manager){
                unset($data['logo']);
                (new MallManager())->where([['id','=',$manager['id']]])->save($data);
            }else{
                (new MallManager())->save($data);
            }

        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }

        return Show::json_show(Status::mini_normal,'ok',[]);
    }

    /**
     * 判断商家是否入驻成功
     * @return void
     */
    public function getManagerApplayStatus2(){
        $openid =$this->request->param('openid','','trim');
        try{
            $info=(new MallManager())->getBaseByWhereOne([['openid','=',$openid]],'*');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$info){
            $apply ='-1';
            $content='';
        }else{
            $apply =$info['status'];
            $content=$info['apply_reason'];
        }
        return Show::json_show(Status::mysql_normal,'返回成功',[
            'status' =>$apply,
            'content' =>$content
        ]);
    }

    /**
     * 商家门店
     * @return \think\response\Json
     */
    public function managerDoors(){
        $openid =$this->request->param('openid','','trim');
        try{
            $list=(new MallManager())->alias('m')
                 ->field('d.*')
            ->join('mall_manager_door d','d.manager_id=m.id')
            ->where([['m.openid','=',$openid],['d.delete_time','=',null]])
            ->select()->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }

        return Show::json_show(Status::mini_normal,'ok',['list'=>$list??[]]);
    }

    public function addManagerDoors(){
        $openid =$this->request->param('openid','','trim');
        $title =$this->request->param('title','','trim');
        $realname =$this->request->param('realname','','trim');
        $mobile =$this->request->param('mobile','','trim');
        $cityarea =$this->request->param('cityarea','','trim');
        $areacode =$this->request->param('areacode','','trim');
        $lat =$this->request->param('lat','','trim');
        $lng =$this->request->param('lng','','trim');
        $store_no =$this->request->param('store_no','','trim');
        $location =$this->request->param('location','','trim');
        $opentime =$this->request->param('opentime','','trim');
        $manageType =$this->request->param('manageType','add','trim');
        $id =$this->request->param('id','0','intval');
        if(!$realname || !$title || !$mobile || !$cityarea || !$location || !$store_no){
            return Show::json_show(Status::mini_error,'请填写完整的门店信息');
        }

        try{
            $managers=(new MallManager())->getBaseByWhereOne([['openid','=',$openid]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$managers){
            return Show::json_show(Status::mini_error,'操作有误');
        }
        $areas =explode(' ',$cityarea);
        $data =[
            'manager_id'=>$managers['id'],
            'title' =>$title,
            'realname' =>$realname,
            'areacode'=>$areacode,
            'mobile'   =>$mobile,
            'opentime' =>$opentime,
            'province' =>$areas[0],
            'city' =>$areas[1],
            'county' =>$areas[2],
            'store_no' =>$store_no,
            'location' =>$location,
            'lat' =>$lat,
            'lng'=>$lng,
            'latlng' =>$lat.','.$lng,
            'status'=>1
        ];
        try{
            if($manageType =='add'){
                (new MallManagerDoor())->save($data);
            }else{
                (new MallManagerDoor())->where([['id','=',$id]])->save($data);
            }

        }catch (\Exception $e){
            return Show::json_show(Status::mini_normal,$e->getMessage());
        }
        return Show::json_show(Status::mini_normal,'ok',[]);
    }

    /**
     * 删除门店
     * @return \think\response\Json
     */
    public function deletedoor(){
        $openid =$this->request->param('openid','','trim');
        $id =$this->request->param('id','','intval');
        try{
           $row= (new MallManagerDoor())->find($id);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_normal,'删除失败');
        }
        if($row){
            $row->delete();
        }
        return Show::json_show(Status::mini_normal,'ok',[]);
    }

    /**
     * 绑定核销员工
     * @return \think\response\Json
     */
    public function BindhxUser(){

        $openid =$this->request->param('openid','','trim');
        $door_id=$this->request->param('door_id','','intval');

        try{
            $row= (new MallManagerDoor())->find($door_id);
            $user= (new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_normal,'查询失败');
        }
        if(!$row){
            return Show::json_show(Status::mini_normal,'查询失败');
        }

        if(!$user){
            return Show::json_show(Status::mini_normal,'请登陆后再次扫码绑定');
        }

        if($user && $user['ishx'] ==1){
            return Show::json_show(Status::mini_normal,'已绑定门店，无需重复绑定');
        }

        (new MallUser())->where([['openid','=',$openid]])->save(['ishx'=>1,'door_id'=>$door_id]);

        return Show::json_show(Status::mini_normal,'核销员工绑定成功',[]);
    }

    /**
     * 我的钱包明细
     * @return mixed
     */
    public function myWallet(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page','1','intval');
        $type =$this->request->param('type','2','intval'); // 2消费明细  3收入明细
        try{
            $where =[['openid','=',$openid]];
            if($type ==2){
                $where[] =[['change_type','in',['0,1']]];
            }else{
                $where[] =[['change_type','in',['3,4']]];
            }
            $list =(new MallAccountLog())->getBaseBylistPage($where,$page,10);
            $member =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
            $withdrawal =(new MallWithdrawal())->where([['openid','=',$openid],['status','=',1]])->sum('money');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }

        return Show::json_show(Status::mysql_normal,'返回成功',[
            'mingxi' =>$list,
            'balance'=>$member['balance'],
            'income' => $member['income'],
            'withdrawal'=>$withdrawal
        ]);
    }

    /**
     * 获取提现规则
     * @return \think\response\Json
     */
    public function getWithdrawalRule(){
        $openid =$this->request->param('openid','','trim');

        try{
            $site = (new SystemConfig())->field('id,value')->where([['group','=','site'],['name','=','withdrawal_desc']])->find();
            $member =(new MallUser())->getBaseByWhereOne([['openid','=',$openid]]);
            $log =(new MallWithdrawal())->getBaseByWhereOne([['openid','=',$openid]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "获取用户信息成功", [
            'desc'=>htmlspecialchars_decode($site['withdrawal_desc']),
            'balance' =>$member['balance'],
            'log'=>$log??[]
        ]);
    }

    /**
     *  可使用红包
     * @return \think\response\Json
     */
    public function getMyCanuseBonus(){
        $openid =$this->request->param('openid','','trim');
        $money =$this->request->param('money','','trim');
        $goods_id =$this->request->param('goods_id','0','intval');
        $where="(ub.openid='$openid' and goods_id='$goods_id' and b.starttime<'".time()."' and b.endtime>'".time()."' and b.status=1
                ) or (ub.openid='$openid' and goods_id=0 and b.starttime<'".time()."' and b.endtime>'".time()."' and b.status=1
                )";
        try{
            $bonus =(new MallUserBonus())->alias('ub')->field('b.id,b.title,b.money,b.maxmoney,b.goods_id')
                ->join('mall_bonus b','b.id=ub.bonus_id')
                ->where($where)
                ->group('b.id')->select()->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        file_put_contents('a.txt',(new MallUserBonus())->alias('ub')->getLastSql().PHP_EOL,8);
        $bonuss=[];
        if($bonus){
            $bonuss[] ='不使用红包';
            $count =count($bonus);
            foreach ($bonus as $k=>$v){
                $kk=$k+1;
                $bonuss[] =$kk.'、'.$v['title'].' '.$v['money'];
                $bonus[$kk]['label'] =$kk.'、'.$v['title'].' '.$v['money'];
                $bonus[$kk]['id'] =$v['id'];
                $bonus[$kk]['money'] =$v['money'];

            }
            $bonus[0]['label'] ='不使用红包';
            $bonus[0]['id'] =0;
        }else{
            $count=0;
        }
        return Show::json_show(Status::mini_normal,'ok',['bonus'=>$bonuss,'count'=>$count,'bonus2'=>$bonus]);
    }

    /**
     * 商家绑定的员工
     * @return \think\response\Json
     */
    public function getManagerByUser(){
        $openid =$this->request->param('openid','','trim');
        try{
            $manager =(new MallManager())->getBaseByWhereOne([['openid','=',$openid],['status','=',1]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if(!$manager){
            return Show::json_show(Status::mini_error,'你还不是商家哦');
        }

        $users =(new MallManagerDoor())->alias('md')->field('u.id,u.nickName,u.mobile,u.avatarUrl,u.realname')
            ->join('mall_user u','u.door_id=md.id')
            ->where([['u.ishx','=',1],['md.manager_id','=',$manager['id']]])
            ->select()
            ->toArray();

        return Show::json_show(Status::mini_normal,'ok',[
            'users'=>$users??[]
        ]);
    }

    /**
     * 取消核销员
     * @return \think\response\Json
     */
    public function canceluser(){
        $id =$this->request->param('id','','trim');
        try{
            $user =(new MallUser())->getBaseById($id);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if(!$user){
            return Show::json_show(Status::mini_error,'不存在该员工');
        }
        try{
            (new MallUser())->where([['id','=',$id]])->save(['ishx'=>0,'door_id'=>0]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        return Show::json_show(Status::mini_normal,'ok',[

        ]);
    }

}